package com.wsc.personalblog.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import java.io.ByteArrayInputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.List;

@Slf4j
public class AliYunOssUtil {
    private static final String endpoint = "";
    private static final String accessKeyId = "";
    private static final String accessKeySecret = "";
    private static final String bucketName = "";
    private static final String prefixPath = "https://"+bucketName+"."+endpoint+".";

    public static void DeleteOne(String fileName) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        System.out.println("开始删除文件："+fileName);
        ossClient.deleteObject(bucketName,fileName);
        ossClient.shutdown();

    }

    public static String upload(byte[] fileByte , String fileName) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 创建PutObjectRequest对象。
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, new ByteArrayInputStream(fileByte));
        ossClient.putObject(putObjectRequest);
        OSSObject ossObject = ossClient.getObject(new GetObjectRequest(bucketName, fileName));
        // 设置文件访问过期时间，这里设置为 1 小时后过期
        Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000);
        // 生成文件访问的预签名 URL
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, fileName);
        request.setExpiration(expiration);
        URL url = ossClient.generatePresignedUrl(request);
        String fileUrl = url.toString();
        System.out.println("文件上传完成！");
        ossClient.shutdown();
        return fileUrl;
    }

    public static String download(String Path){
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            OSSObject object = ossClient.getObject(bucketName, Path);
            byte[] content = IOUtils.toByteArray(object.getObjectContent());
            String base64PhotoFile = Base64.getEncoder().encodeToString(content);
            return base64PhotoFile;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }  finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
